<template>
  <LayOutLogin form-title-name="忘记密码" :is-show-third-login="false">
    <template v-slot:form>
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate">
        <FormItem class="form-item-user" prop="userName">
          <i-input
            type="text"
            style="width: 100%"
            placeholder="姓名"
            v-model="formValidate.userName"
          >
          </i-input>
        </FormItem>
        <FormItem class="form-item-password" prop="userAccount">
          <i-input
            type="text"
            style="width: 100%"
            placeholder="手机号/邮箱"
            v-model="formValidate.userAccount">
          </i-input>
        </FormItem>
        <FormItem class="form-item-captcha" prop="password">
          <i-input
            type="text"
            style="width: 100%"
            placeholder="验证码"
            v-model="formValidate.password"
          >
            <template v-slot:suffix>
              <span v-if="isGetCaptcha" key="captchaYes" v-text="useCountdownTime"></span>
              <span v-text="captchaText" @click="privateGetCaptcha('formValidate')" v-else key="captchaNo"></span>
            </template>
          </i-input>
        </FormItem>
        <FormItem class="form-item-newpsw" v-if="isInputResetPwd" prop="newPassword">
          <i-input
            type="password"
            style="width: 100%"
            placeholder="新密码"
            v-model="formValidate.newPassword"
          >
          </i-input>
        </FormItem>
        <FormItem class="form-item-newpsw" v-if="isInputResetPwd" prop="checkPsw">
          <i-input
            type="password"
            style="width: 100%"
            placeholder="确认密码"
            @on-enter="handleSubmit('formValidate')"
            v-model="formValidate.checkPsw"
          >
          </i-input>
        </FormItem>
        <FormItem class="ivu-form-btn">
          <Button
            type="primary"
            :loading="loading"
            long
            style="background-color: #2878FF"
            @click="handleSubmit('formValidate')">重置密码
          </Button>
        </FormItem>
        <FormItem class="form-other-login">
          <span></span>
          <span @click="handleAccountLogin()">返回账号登录</span>
        </FormItem>
      </Form>
    </template>
  </LayOutLogin>
</template>

<script>
import { goLogin } from '../../router'
import { sendMailVerificationCode, sendPhoneVerificationCode, retrievePasswordByMail, retrievePasswordByPhone } from '../../api/modules/system/msgTemplate'
import message from '../../utils/message'
import { JSEncrypt } from 'jsencrypt'
import { getRsaPublicKey } from '../../api/modules/login/login'
import { isPhone, isEmail } from '../../utils/verification'

export default {
  name: 'LoginForgetPassword',
  data () {
    // 自定义确认密码验证
    const validateConfirm = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('确认密码不能为空'))
      } else if (value !== this.formValidate.newPassword) {
        callback(new Error('两次输入密码不相符'))
      } else {
        callback()
      }
    }
    // 自定义手机号、邮箱验证
    const validateAccount = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('手机号或邮箱不能为空'))
      } else if (isPhone(value)) {
        callback()
      } else if (isEmail(value)) {
        callback()
      } else {
        callback(new Error('手机号或邮箱格式错误'))
      }
    }
    return {
      formValidate: {
        userAccount: '',
        rsaKey: '',
        password: '',
        newPassword: '',
        checkPsw: '',
        userName: ''
      },
      ruleValidate: {
        userAccount: [{ validator: validateAccount, trigger: 'blur' }],
        password: [{ required: true, message: '验证码不能为空', trigger: 'blur' },
          { min: 6, trigger: 'blur', message: '验证码为6位数' }],
        newPassword: [{ required: true, message: '新密码不能为空', trigger: 'blur' },
          { min: 6, trigger: 'change', message: '密码不能少于6位数' }],
        checkPsw: [{ validator: validateConfirm, trigger: 'blur' }]
      },
      formCode: {
        account: '',
        rsaKey: '',
        verificationCode: ''
      },
      loading: false,
      isGetCaptcha: false,
      captchaText: '获取验证码',
      timeId: null,
      countdownTime: 60
    }
  },
  computed: {
    useCountdownTime () {
      return `重新发送(${this.countdownTime}) `
    },
    // 是否显示密码框
    isInputResetPwd () {
      return this.formValidate.password.length >= 6 && this.isGetCaptcha
    }
  },
  methods: {
    /**
     * 返回登录
     */
    handleAccountLogin () {
      goLogin()
    },
    /**
     * 提交表单
     */
    handleSubmit (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          const userAccount = this.formValidate.userAccount
          if (isPhone(userAccount)) {
            this.$_updateSubmit(1)
          } else if (isEmail(userAccount)) {
            this.$_updateSubmit(2)
          } else {}
        } else {
          message.message.error('输入数据格式错误，请检查后重试')
        }
      })
    },
    /**
     * 提交数据
     */
    $_updateSubmit (type) {
      this.loading = true
      const { newPassword, password, userAccount, rsaKey } = this.formValidate
      const params = {
        newPassword,
        password,
        userAccount,
        rsaKey
      }
      if (type === 1) {
        retrievePasswordByPhone(params).then(data => {
          message.message.success(data.message + ',即将为你跳转到登录页', { duration: 3 }, () => {
            this.loading = false
            goLogin()
          })
        }).catch(error => {
          message.message.error(error.message || '系统异常')
          this.loading = false
        })
      } else {
        retrievePasswordByMail(params).then(data => {
          message.message.success(data.message + ',即将为你跳转到登录页', { duration: 3 }, () => {
            this.loading = false
            goLogin()
          })
        }).catch(error => {
          message.message.error(error.message || '系统异常')
          this.loading = false
        })
      }
    },
    /**
       * 获取验证码
       */
    privateGetCaptcha (name) {
      this.$refs[name].validateField('userAccount', (error) => {
        if (error) {
          message.message.error('手机号或邮箱不能为空或格式错误')
        } else {
          const userAccount = this.formValidate.userAccount
          if (isPhone(userAccount)) {
            this.$_getVerification(1)
          } else if (isEmail(userAccount)) {
            this.$_getVerification(2)
          } else {}
        }
      })
    },
    /**
     * 获取验证码
     */
    $_getVerification (type = 1) {
      // 开始倒计时
      this.cationCodeTime()
      // 获取公钥
      getRsaPublicKey().then(({ data }) => {
        const { rsaKey, publicKey } = data
        this.formValidate.rsaKey = rsaKey
        const account = this.formValidate.userAccount
        const enc = new JSEncrypt()
        enc.setPublicKey(publicKey)
        const verificationCode = enc.encrypt(account)
        const params = {
          account,
          rsaKey,
          verificationCode
        }
        return params
      }).then(data => {
        // type为1表示手机验证码，反之邮箱验证码
        if (type === 1) {
          return sendPhoneVerificationCode(data)
        } else {
          return sendMailVerificationCode(data)
        }
      }).then(data => {
        message.message.success(data.message)
      }).catch(error => {
        message.message.error(error.message || '系统错误')
        this.isGetCaptcha = false
      })
    },
    /**
     * 验证码计时
     */
    cationCodeTime () {
      this.isGetCaptcha = true
      this.timeId = setInterval(() => {
        this.countdownTime -= 1
      }, 1000)
    }
  },
  components: {
    LayOutLogin: () => import('./LayOutLogin')
  },
  /**
   * 组件销毁前触发
   */
  beforeDestroy () {
    clearInterval(this.timeId)
  },
  watch: {
    countdownTime (val) {
      if (val === 0) {
        // 移除监听，重新赋值
        clearInterval(this.timeId)
        this.countdownTime = 60
        this.isGetCaptcha = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
  @import "../../assets/styles/scss/mixin";
  /deep/ .ivu-input{
    border-radius: 0px;
    border:1px solid rgba(230,230,230,1);
    height: .5rem;
  }
  .ivu-form{
    margin-top: .7rem;
    /*margin-top: 6.48%;*/
  }
  .ivu-btn{
    border-radius: 0px;
    height: .5rem;
  }
  .ivu-form-item{
    margin-bottom: .4rem;
  }
  .form-item-other{
  /deep/ .ivu-form-item-content{
    line-height: 0;
  @include flexMixer(space-between);
    color: #B3B3B3;
  }
  }
  /deep/ .form-item-captcha{
  .ivu-input-suffix{
    width: auto;
    color: #396AFE;
    margin-right: .16rem;
    line-height: .5rem;
    cursor: pointer;
  }
  }
  .ivu-form-btn{
    margin-bottom: 0px;
  }
  /deep/ .form-other-login{
    margin-bottom: 0;
    height: .5rem;
    cursor: pointer;
  /deep/ .ivu-form-item-content{
    height: 100%;
    width: 100%;
  @include flexMixer(space-between);
    color: #B3B3B3;
  }
  }
</style>
